package com.dq.controller.api.pay;

import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.util.*;

@Component
public class SignMd5 {

  public static Map sign(Map treeMap, String key) {
    String sort = "";
    Iterator it = treeMap.keySet().iterator();
    while (it.hasNext()) {
      String text = (String) it.next();
      sort = sort + text + "=" + treeMap.get(text).toString() + "&";
    }
    if ((sort != null) && (!("".equals(sort)))) {
      sort = sort.substring(0, sort.length() - 1);
    }
    String signText = sort + "&key=" + key;

    treeMap.put("sign", DigestUtils.md5Hex(signText).toUpperCase());
    return treeMap;
  }

  public static String map2Xmlstring(Map<String,String> map) {
    StringBuffer sb = new StringBuffer("");
    sb.append("<xml>");

    Set<String> set = map.keySet();
    for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
      String key = it.next();
      Object value = map.get(key);
      sb.append("<").append(key).append(">");
      sb.append(value);
      sb.append("</").append(key).append(">");
    }
    sb.append("</xml>");
    return sb.toString();
  }

  public static Map<String,Object> xmlString2Map(String xmlStr){
    Map<String,Object> map = new HashMap<String,Object>();
    Document doc;
    try {
      doc = DocumentHelper.parseText(xmlStr);
      Element el = doc.getRootElement();
      map = recGetXmlElementValue(el,map);
    } catch (DocumentException e) {
      e.printStackTrace();
    }
    return map;
  }

  private static Map<String, Object> recGetXmlElementValue(Element ele, Map<String, Object> map) {
    List<Element> eleList = ele.elements();
    if (eleList.size() == 0) {
      map.put(ele.getName(), ele.getTextTrim());
      return map;
    } else {
      for (Iterator<Element> iter = eleList.iterator(); iter.hasNext(); ) {
        Element innerEle = iter.next();
        recGetXmlElementValue(innerEle, map);
      }
      return map;
    }
  }

  public static String mapToXml(TreeMap<String, String> data) throws Exception {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    org.w3c.dom.Document document = documentBuilder.newDocument();
    org.w3c.dom.Element root = document.createElement("xml");
    document.appendChild(root);
    for (String key : data.keySet()) {
      String value = data.get(key);
      if (value == null) {
        value = "";
      }
      value = value.trim();
      org.w3c.dom.Element filed = document.createElement(key);
      filed.appendChild(document.createTextNode(value));
      root.appendChild(filed);
    }
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    transformer.transform(source, result);
    String output = writer.getBuffer().toString();
    try {
      writer.close();
    } catch (Exception ex) {
    }
    return output;
  }

}
